package com.itheima.filter;

import com.itheima.utils.CurrentHolder;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

@WebFilter("/*")
public class Tokenfilter implements Filter {
    private static final Logger log = LoggerFactory.getLogger(Tokenfilter.class);

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String requestURI = request.getRequestURI();

        if (requestURI.contains("/login")){
            log.info("登录操作，放行...");
            filterChain.doFilter(request,response);
            return;
        }

        String token = request.getHeader("token");

        if (token == null || token.isEmpty()){
            log.info("请求头中不包含token，返回401...");

            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

            return;
        }

        try{
            log.info("请求头中包含token，进行解析...");
            Claims claims = JwtUtils.parseToken(token);
            Integer empId = Integer.valueOf(claims.get("id").toString());
            CurrentHolder.setCurrentId(empId);
        }catch (Exception e){
            log.info("解析token失败，返回401...");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

        log.info("token有效，放行...");
        filterChain.doFilter(request,response);

        CurrentHolder.remove();
    }
}
